<?php
namespace app\home\controller\order;

use think\Controller;
use think\Db;
use addons\epay\library\Service;

class Cart extends Controller
{
    public function __construct()
    {
         // 继承父类
         parent::__construct();
         $this->OrderModel = model('Order.Order');
        $this->TypeModel = model('Product.Type');
        // 商品模型
        $this->ProductModel = model('Product.Product');
        $this->HireModel = model('Hire.Hire');
        //  * 订单商品模型
        $this->OrderProductModel = model('Order.Product');
        // 用户模型
        $this->BusinessModel = model('Business.Business');

        // 购物车订单模型
        $this->OrderCartModel = model("Order.Cart");

        $this->Service = new Service();

        $this->config = Service::getConfig();


        

    
           // 判断用户是否存在
        if($this->request->isAjax())
        {
             //接收用户id
             $this->busid = $this->request->param('busid', 0, 'trim');
             

            $business = $this->BusinessModel->find($this->busid);
            

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
        }
        // 获取系统配置中的选项
        $this->url = config("site.realm") ? config("site.realm") : "";

    }

    public function badge()
    {
        if($this->request->isAjax())
        {
            $busid = $this->request->param("busid",0,"trim");
           

            // 查找购物车商品表，看当前用户买的商品总数是多少，返回回来，给前端
            $pronum = $this->OrderCartModel->where(["busid"=>$busid])->sum("pronum");
            // $num = $this->OrderCartModel->where(["busid"=>$busid])->sum("num");
            // $sum = bcadd($pronum,$num); 
            // var_dump($pronum);

            $this->success("返回当前用户下订单的商品总数",null,$pronum);
            exit;

          
        
          
        }
    }

    // 购物车列表数据
    public function cartindex()
    {
        if($this->request->isAjax())
        {
            $busid = $this->request->param("busid",0,"trim");

            // 根据id去链表查询商品信息还有客户信息
            // alias改模型起别名
            $proids = Db::name("product")->column("id");
            $proidsValue = implode(",",$proids);
            $cartproinfo = $this->OrderCartModel->where(["busid"=>$busid])->order("id desc")->select();
            $list = [];
            foreach($cartproinfo as $item)
            {
                if(!is_null($item["proid"]))
                {
                    $item["goods"] = collection([ $this->ProductModel->find($item["proid"])]);
                    $list[] = $item;

                }
                else
                {
                    $item["goods"] = collection( [$this->HireModel->find($item["hireid"])]);
                    $list[] = $item;
                }


            }


            $this->success("返回购物车首页列表信息",null,$list);

           

        }
    }

    // 购物车商品添加
    public function add()
    {
        if($this->request->isAjax())
        {
            
            $proid = $this->request->param('proid', 0, 'trim');
            $hireid = $this->request->param('hireid', 0, 'trim');
            $soure = $this->request->param('soure', 0, 'trim');
            

            if($soure=="hire")
            {

                $hire = $this->HireModel->find($hireid);
               
                if(!$hire)
                {
                    $this->error('商品不存在');
                    exit;
                }

                
          
                //组装数据
                $CartData = [];
                $result = false;

                //先判断购物车是否有当前的商品记录
                $where = [
                    'hireid' => $hireid,
                    'busid' => $this->busid
                ];


                $cart = $this->OrderCartModel->where($where)->find();
            
           

            if($cart)
            {
            
                //加完后的数量
                $pronum = $cart['num']+1;

                $total = bcmul($cart['price'], $pronum);

                $CartData = [
                    'id' => $cart['id'],
                    'busid' => $cart['busid'],
                    'hireid' => $cart['hireid'],
                    'price' => $cart['price'],
                    'pronum' => $pronum,
                    'total' => $total,
                    "stoid"=>$cart["stoid"],
                    "checked"=>1
                ];

                

                //更新语句
                $result = $this->OrderCartModel->validate('common/Order/Cart.hire')->isUpdate(true)->save($CartData);
                if(!$result)
                {
                    $this->error("加入购物车失败");
                    exit;
                }else
                {
                    $this->success("加入购物车成功");
                    exit;
                }
            }else
            {
                
                
                $CartData = [
                    'busid' => $this->busid,
                    'hireid' => $hireid,
                    'pronum' => 1,
                    'price' => $hire['price'],
                    'total' => $hire['price'],
                    "stoid"=>$hire["stoid"],
                    "checked"=>1


                ];
                

                //执行插入语句
                $result = $this->OrderCartModel->validate('common/Order/Cart.hire')->save($CartData);
                if($result === FALSE)
                {
                    $this->error($this->OrderCartModel->getError());
                    exit;
                }else
                {
                    $this->success('加入购物车成功', '/order/order/cart.hire');
                    exit;
                }
    
    
    
            }

          
            }else
            {
                //判断商品是否存在
                $product = $this->ProductModel->find($proid);
                

                if(!$product)
                {
                    $this->error('商品不存在');
                    exit;
                
                }

                
          
                //组装数据
                $CartData = [];
                $result = false;

                //先判断购物车是否有当前的商品记录
                $where = [
                    'proid' => $proid,
                    'busid' => $this->busid
                ];


                $cart = $this->OrderCartModel->where($where)->find();
        
           

            if($cart)
            {
                //加完后的数量
                $pronum = $cart['pronum']+1;

                $total = bcmul($cart['price'], $pronum);

                $CartData = [
                    'id' => $cart['id'],
                    'busid' => $cart['busid'],
                    'proid' => $cart['proid'],
                    'price' => $cart['price'],
                    'pronum' => $pronum,
                    'total' => $total,
                    "stoid"=>$cart["stoid"],
                    "checked"=>1


                ];

                //更新语句
                $result = $this->OrderCartModel->validate('common/Order/Cart.product')->isUpdate(true)->save($CartData);
                if(!$result)
                {
                    $this->error("加入购物车失败");
                    exit;
                }else
                {
                    $this->success("加入购物车成功");
                    exit;
                }
            }else
            {
                $CartData = [
                    'busid' => $this->busid,
                    'proid' => $proid,
                    'pronum' => 1,
                    'price' => $product['price'],
                    'total' => $product['price'],
                    'stoid' => $product['stoid'],
                    "checked"=>1

                    
                ];
                
                //执行插入语句
                $result = $this->OrderCartModel->validate('common/Order/Cart.product')->save($CartData);
                if(!$result)
                {
                    $this->error("加入购物车失败");
                    exit;
                }else
                {
                    $this->success("加入购物车成功");
                    
                    exit;
                }
            }

            if($result === FALSE)
            {
                $this->error($this->OrderCartModel->getError());
                exit;
            }else
            {
                $this->success('加入购物车成功', '/order/order/cart');
                exit;
            }


            }
            
         

        }
    }

      //购物车编辑
      public function edit()
      {
          if($this->request->isAjax())
          {
              $id = $this->request->param('id', 0, 'trim');
              $pronum = $this->request->param('pronum', 0, 'trim');

            
              

             
  
              if($pronum <= 0)
              {
                  $this->error('购物车数量不能小于0');
                  exit;
              }
  
              // 先判断购物车记录是否存在
              $where = [
                  'id' => $id,
                  'busid' => $this->busid,
              ];
  
              $cart = $this->OrderCartModel->where($where)->find();
  
              if(!$cart)
              {
                  $this->error('购物车记录不存在');
                  exit;
              }
  
            //   商城的数据(手表数据为空)
              if(is_null($cart["proid"]))
              {

                    
                    $data = [
                        'id'=>$cart['id'],
                        'busid'=>$cart['busid'],
                        'hireid'=>$cart['hireid'],
                        'pronum'=>$pronum,
                        'price'=>$cart['price'],
                    ];
                

                    //合计总价
                $data['total'] = bcmul($cart['price'], $pronum);
                
                //更新
                $result = $this->OrderCartModel->validate('common/Order/Cart.hire')->isUpdate(true)->save($data);
    
                if($result === FALSE)
                {
                    $this->error($this->OrderCartModel->getError());
                    exit;
                }else
                {
                    $this->success('更新购物车成功',null,true);
                    exit;
                }

              }else
              {
                // 
                $data = [
                    'id'=>$cart['id'],
                    'busid'=>$cart['busid'],
                    'proid'=>$cart['proid'],
                    'pronum'=>$pronum,
                    'price'=>$cart['price'],
                ];

                

                  //合计总价
              $data['total'] = bcmul($cart['price'], $pronum);
              
              //更新
              $result = $this->OrderCartModel->validate('common/Order/Cart.product')->isUpdate(true)->save($data);
  
              if($result === FALSE)
              {
                  $this->error($this->OrderCartModel->getError());
                  exit;
              }else
              {
                $this->success('更新购物车成功',null,true);
                exit;
              }
              }

            
  
            
          }
      }
    

     // 购物车删除
     public function delete()
     {
         if($this->request->isAjax())
         {
             $params = $this->request->param();

           
            
             $busid = $params["busid"];

             $ids = $params["cartids"];

             $idsValue = implode(",",$ids);


            //  //判断购物车记录是否存在
            //  $where = [
            //      'id' => $cartids,
            //      'busid' => $this->busid,
            //  ];
 
             $cart = $this->OrderCartModel->whereIn("id",$idsValue)->where("busid",$busid)->select();
             if(!$cart)
             {
                 $this->error('购物车记录不存在');
                 exit;
             }
 
             //删除
             $result = $this->OrderCartModel->destroy($idsValue,true);
 
             if($result === FALSE)
             {
                 $this->error('删除失败');
                 exit;
             }else
             {
                 $this->success('删除成功');
                 exit;
             }
         }
     }

    //购物车下单
    public function cartadds()
    {
        if($this->request->isAjax())
        {
            $params = $this->request->param();

         

            $cartids = implode(",",$params["cartids"]);

            $busid = $params["busid"];

            $business = $this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error("用户不存在");
                exit;
            }

            $where = [
                'cart.id' => ['in', $cartids]
            ];

            // 购物车列表
            $cartlist = $this->OrderCartModel->with(['product','hire'])->where($where)->select();

               // 判断库存够不够
               foreach($cartlist as $cart)
               {
                   if(!is_null($cart["proid"]))
                   {
                       if($cart['product']['stock'] < $cart['pronum'])
                       {
                           $this->error($cart['product']['brankname_text'].$cart['product']['btypename_text'].$cart['product']['code'] . "库存不足，无法下单");
                           exit;
                       }
                   }else
                   {
                       if($cart['hire']['stock'] < $cart['pronum'])
                       {
       
                  
                           $this->error($cart['hire']['brankname_text'].$cart['hire']['btypename_text'].$cart['hire']['code'] . "库存不足，无法下单");
                           exit;
                       }
                   }
               }

            // 订单表 插入
            // 订单商品表 插入
            // 商品表 更新
            // 用户表 更新
            // 用户的消费记录表 插入
            // 购物车 删除

            $OrderModel = model('Order.Order');
            $OrderProductModel = model('Order.Product');
            $ProductModel = model('Product.Product');
            $RecordModel = model('Business.Record');
            // $BusinessModel = model('Business.Business');
            $OrderCartModel = model('Order.Cart');

            // 开启事务
            $OrderModel->startTrans();
            $OrderProductModel->startTrans();
            $ProductModel->startTrans();
            $RecordModel->startTrans();
            // $BusinessModel->startTrans();
            $OrderCartModel->startTrans();


            // 生成订单编号
            $code = build_code('FA');

            //组装数据
            $OrderData = [
                'code' => $code,
                'busid' => $business['id'],
                // 'businessaddrid' => $addrid,
                'amount' => 999,
                // 'remark' => $remark,
                'status' => 1,
                // 'adminid' => $business['adminid']
            ];

            // 插入订单数据
            $OrderStatus = $OrderModel->save($OrderData);

            if($OrderStatus === FALSE)
            {
                $this->error($OrderModel->getError());
                exit;
            }

            //整理订单商品数据
            $OrderProductData = [];

            //整理商品表更新库存的数据
            $ProductData = [];
            $HireData = [];

            // var_dump(collection($cartlist)->toArray());
            // exit;
            $a= 0;
            foreach($cartlist as $item)
            {
             
                if(!is_null($item["proid"]) || !is_null($item["hireid"]))
                {
                    // $a += $item['price'];
                    //插入
                    $OrderProductData[] = [
                        'orderid' => $OrderModel->id, //获取上一步插入的自增id
                        'proid'=>$item['proid'],
                        'pronum'=>$item['pronum'],
                        'price'=> $item["price"],
                        'total'=>$item["price"],
                        "hireid"=>$item["hireid"]
                    ];
    


                }
              
           

                //更新  商品库存 -  购买数量

             

                

              
            }

        $result = [];

        foreach ($OrderProductData as $key) {
            $orderId = $key["orderid"];

            if (!isset($result[$orderId])) {
                // 如果结果数组中还没有这个订单的记录，则直接添加
                $result[$orderId] = $key;
            } else {
                // 如果结果数组中已经有这个订单的记录，则将相应字段相加
                $result[$orderId]["pronum"] += $key["pronum"];
                $result[$orderId]["price"] = bcadd($result[$orderId]["price"], $key["price"], 2);
                $result[$orderId]["total"] = bcadd($result[$orderId]["total"], $key["total"], 2);

                // 如果hireid字段不同，则选择非空的hireid
                if ($key["hireid"] !== null) {
                    $result[$orderId]["hireid"] = $key["hireid"];
                }
                if ($key["proid"] !== null) {
                    $result[$orderId]["proid"] = $key["proid"];
                }
            }
           }

            var_dump($result);
            // var_dump($HireData);
            exit;
          
        }
    }
          

    


    // 查看购物车刚刚下的订单
    public function downorder()
    {
        $busid = $this->request->param("busid",0,"trim");
        $orderid = $this->request->param("orderid",0,"trim");

        $business = $this->BusinessModel->find($busid);
        if(!$business)
        {
            $this->error("用户账号不存在");
            exit;
        }
        
        $info = $this->OrderProductModel->with(["proinfo","hireinfo"])->where("orderid",$orderid)->select();
        
        $this->success("返回刚下单的信息",null,$info);
    }

    // 购物车支付回调的订单
    public function paycallback()
    {
        if($this->request->isPost())
        {
            $orderid = $this->request->param("orderid",0,"trim");
            $busid = $this->request->param("busid",0,"trim");
            $business = $this->BusinessModel->find($busid);
            if(!$business)
            {
                $this->error("用户不存在");
                exit;
            }


            $order = $this->OrderModel->where(["id"=>$orderid,"busid"=>$busid,"status"=>1])->find();
            if(!$order)
            {
                $this->error("订单不存在");
                exit;
            }



            $title = "奢总会购物车总订单";
            $notify_url =  $this->config['notify_url'];
            $return_url  =$this->config["return_url"];
            
            // 订单号
            $params = [
                'amount'=>$order["amount"],
                'orderid'=>$order["code"],
                'type'=>"wechat",
                'title'=>$title,
                'notifyurl'=> $notify_url,
                'returnurl'=>$return_url,
                'method'=>"mini",
                'openid'=> $this->openid
            ];

            // var_dump($params);
            // exit;

            $Payinfo = Service::submitOrder($params);
            $Payinfo["orderid"] = $order["id"];


            // 如果订单存在的话就去改变订单状态

            $validate = [
                [
                    "id"=>"require",
                    "status"=>"require"
                ],
                [
                    "id.require"=>"订单ID未知",
                    "status.require"=>"订单状态未知"
                ]
                ];

            $result = $this->OrderModel->validate(...$validate)->isUpdate(true)->save(["id"=>$orderid,"status"=>2]);

            if($result==false)
            {
                $this->error("支付失败");
                exit;
            }
            






        }
    }

    



  


}